package com.smart.manager.task;


import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ObjUtil;
import com.smart.common.annotation.TaskBean;
import com.smart.common.annotation.TaskMethod;
import com.smart.common.entities.domain.TaskResult;
import com.smart.manager.member.entities.models.MemberMaterialPig;
import com.smart.manager.member.entities.models.MemberMaterialPigState;
import com.smart.manager.member.entities.models.query.QMemberMaterialPig;
import com.smart.manager.product.entities.enums.PigStatus;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author leo
 * @date 2023/11/01
 */
@Log4j2
@Component
@TaskBean
@RequiredArgsConstructor
public class EveryDayTask {

    @TaskMethod(title = "每天记录猪仔状态")
    public synchronized TaskResult cleanRemoveRecord() {
        try {
            LocalDate date = LocalDate.now();
            List<MemberMaterialPig> pigs = new QMemberMaterialPig().status.eq(PigStatus.NORMAL).findList();
        ArrayList<MemberMaterialPigState> states = new ArrayList<>();
        for (MemberMaterialPig pig : pigs) {
            MemberMaterialPigState pigState = new MemberMaterialPigState()
                    .setPigId(pig.getId())
                    .setTiming(date)
                    .setTemp("暂无")
                    .setStep(0);
            Opt.ofNullable(pig.getRfid()).ifPresent(x->{
                Opt.ofNullable(x.getTemperature()).ifPresent(pigState::setTemp);
                Opt.ofNullable(x.getShake()).ifPresent(c->pigState.setStep(Integer.valueOf(c)));
            });
            states.add(pigState);
        }
        if (ObjUtil.isNotNull(states)){
            DB.insertAll(states);
        }
        }catch (Exception e){
            e.printStackTrace();
        }
        return new TaskResult(true, "记录成功");
    }
}
